package com.hxkj.service.article.impl;


import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.*;
import com.hxkj.domain.enums.TemplteExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.service.FriendlyLinkService;
import com.hxkj.service.NavigationService;
import com.hxkj.service.article.FreeMakerService;
import com.hxkj.token.utils.TokenUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 模板解析实现类
 * <p>
 * Created by yaosy on 2018年6月19日09:27:00
 */
@Service
@Slf4j
public class FreeMakerServiceImpl implements FreeMakerService {


    @Autowired
    private FreeMarkerServiceClient freeMarkerServiceClient;

    @Autowired
    private NavigationService navigationService;
    @Autowired
    private FriendlyLinkService friendlyLinkService;
    @Autowired
    private ArticleServiceClient articleServiceClient;
    @Autowired
    private UniversalServiceClient universalServiceClient;
    @Autowired
    private ColumnServiceClient columnServiceClient;
    @Autowired
    private LeafletServiceClient leafletServiceClient;
    @Autowired
    private ManuscriptServiceClient manuscriptServiceClient;




    @Value("${cms.path}")
    private String Path;

    @Value("${cms.pathUrl}")
    private String PathUrl;

    @Value("${cms.tpl}")
    private String Tpl;

    @Value("${urlapi.urlPort}")
    private String urlPort;

    private String htmlPath="";



    /***
     * data 封装数据
     * templetId 模板id
     * **/
    @Override
    public JSONObject analyze(FreeMarker freeMarker) throws Exception {
        ResultDataStruct resultDataStruct = new ResultDataStruct();
        try{
            if(freeMarker == null){
                throw new CustomException(TemplteExceptionEnum.TEMPLTE_DATA_BLANK);
            }
            if (freeMarker.getTempletId() == null) {
                throw new CustomException(TemplteExceptionEnum.TEMPLTE_NOT_ID);
            }
            if (freeMarker.getMaps() == null) {
                throw new CustomException(TemplteExceptionEnum.TEMPLTE_PARSING_DATA_BLANK);
            }
            if (freeMarker.getSiteId() == null) {
                throw new CustomException(TemplteExceptionEnum.TEMPLTE_NOT_SITEID);
            }
            if (freeMarker.getChannelId() == null) {
                throw new CustomException(TemplteExceptionEnum.TEMPLTE_NOT_ID);
            }
            //导航栏
            Navigation navigation = new Navigation();
            navigation.setSiteId(freeMarker.getSiteId());
            navigation.setIsEnable(0);
            List<NavigationTree> navigationTreeList = navigationService.getNavigationList(navigation).getData();

            //友情链接
            FriendlyLink friendlyLink = new FriendlyLink();
            friendlyLink.setSiteId(freeMarker.getSiteId());
            PageTo pageTo = new PageTo();
            List<FriendlyLink> friendlyLinkList = friendlyLinkService.getFriendlyLinkList(friendlyLink, pageTo).getData();
            //查询  文章推荐 不要分类 取前10 条
            Article article1 = new Article();
            article1.setSiteId(freeMarker.getSiteId());
            ResultDataStruct<List<Article>> list1 = articleServiceClient.getHotArticle(article1);
            List<Article> hotArticle = list1.getData();


            //Mr.zheng:如果是期权百科频道，则封装热门百科，即5级推荐
            Article article = new Article();
            article.setSiteId(freeMarker.getSiteId());
            article.setLocationLevel(5);
            //查询 热门百科 3篇
            List<Article> hotCyclopedia = articleServiceClient.getArticle1(article).getData();


            Map maps = freeMarker.getMaps();

            if (maps.containsKey("optionColumn")) {
                OptionColumnTree optionColumnTree = (OptionColumnTree) maps.get("optionColumn");
                optionColumnTree.setChecked(0);
                if (optionColumnTree.getColumnId() == freeMarker.getColumnId()) {
                    optionColumnTree.setChecked(1);
                } else {
                    optionColumnTree = addStauts(optionColumnTree, freeMarker.getColumnId());
                }
                maps.put("optionColumn", optionColumnTree);
            }

            //Mr.zheng:站点ID解析
            String siteId = String.valueOf(freeMarker.getSiteId());
            maps.put("siteId", siteId);

            //网站信息 模板解析
            SiteUniversal siteUniversal = new SiteUniversal();
            siteUniversal.setSiteId(freeMarker.getSiteId());
            siteUniversal = universalServiceClient.get(siteUniversal).getData();

            // 单页 tags聚合所有标签解析
            Manuscript man = new Manuscript();
            man.setChannelId("tagsjh");
            man.setSiteId(freeMarker.getSiteId());
            Manuscript manu = manuscriptServiceClient.getManuscript(man).getData();
            if (manu != null) {
                maps.put("TagJh", "TAG聚合");
                maps.put("TagPath", manu.getUrlPath());
            }
            //面包屑 --chenfangzhou
            //文章详情和文章列表
            if (freeMarker.getColumnId() != null) {
                Column column1 = new Column();
                column1.setColumnId(freeMarker.getColumnId());
                List<Column> NavColumnList = columnServiceClient.getTopParentColumn(column1);
                maps.put("NavColumnList", NavColumnList);
                // 导航栏的选中状态 分为文章详情和分类列表单独处理 比对导航栏名称和类型的顶级分类
                for (NavigationTree nav : navigationTreeList) {
                    if (nav.getNavigationName().equals(NavColumnList.get(1).getColumnName())) {
                        nav.setChecked(0);
                    }
                }
            }else{
                //没有传分类id的为单页
                List<Column> NavColumnList = new ArrayList<>();
                Column column1 = new Column();
                column1.setColumnName("首页");
                column1.setManuscriptPath(htmlPath+"/hxypt/index.html");
                NavColumnList.add(column1);
                maps.put("NavColumnList",NavColumnList);
            }
            //Mr.zheng:静态资源文件绝对路径
            maps.put("PATH", Path + PathUrl);
            //Mr.zheng:图片资源路径
            maps.put("ASSET", Path);
            //Mr.zheng:模板资源路径
            maps.put("TPL", Path + Tpl);
            //Mr.zheng:动态接口ip
            maps.put("URL", urlPort);
            //公共模块,导航栏,友情链接,热门文章,热词标签、热门百科
            maps.put("navigationTreeList", navigationTreeList);
            maps.put("linkList", friendlyLinkList);
            maps.put("hotArticle", hotArticle);
            //maps.put("leafletList",leafletList);
            maps.put("hotCyclopedia", hotCyclopedia);
            //网站信息
            maps.put("siteUniversal", siteUniversal);
            freeMarker.setMaps(maps);

            //Map map =  JSON.parseObject(freeMarker.getData());
            //freeMarker.setMaps(freeMarker.getMaps());

            resultDataStruct = freeMarkerServiceClient.analyze(freeMarker);
            if (resultDataStruct.getData() == null) {
                //throw new CustomException(TemplteExceptionEnum.TEMPLTE_NOT_MSG);
                throw new CustomException(resultDataStruct.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage());
            //throw new CustomException(e.getMessage()+"---"+ e.getCause());
        }
        return (JSONObject) resultDataStruct.getData();
    }


    private OptionColumnTree addStauts(OptionColumnTree optionColumnTree, Long columnId) {
        if (optionColumnTree.getChildren() != null) {
            for (OptionColumnTree columnTree : optionColumnTree.getChildren()) {
                columnTree.setChecked(0);
                if (columnTree.getColumnId() == columnId) {
                    columnTree.setChecked(1);
                } else {
                    columnTree.setChecked(0);
                    columnTree = addStauts(columnTree,columnId);
                }
            }
        }
        return optionColumnTree;
    }
}
